import React, { Component } from 'react';
import axios from 'axios';
import $ from 'jquery';
import moment from 'moment';
import Cookie from 'js-cookie'
import {  
  List
} from "antd";
import './Feed.less';
import '../../style/common.less';

const ListItem = List.Item;
const ListItemMeta = List.Item.Meta;

class Feed extends Component {
  constructor(props) {
    super(props);
    const useCache = Cookie.get('useCache');
    console.log(useCache);
    
    this.state = {
      feedData: [],
      loading: false,
      useCache: useCache === 'true'
    }
    this.props.bindChild(this);
  }

  refreshFeed = (cb) => {
    this.setState({
      feedData: [],
      useCache: false
    })
    Cookie.set('useCache', 'false');
    localStorage.removeItem('feed');
    setTimeout(() => {
      this.getFeedList('https://www.xuejichang.cn/feed/zhangxinxu', 0)
        .then(() => {
        return this.getFeedList('https://www.xuejichang.cn/feed/ruanyifeng', 1)
      }).then(() => {
        cb && cb()
      })
    }, 0);
  }

  readData = () => {
    const localFeed = localStorage.getItem('feed');
    if (localFeed) {
      return JSON.parse(localFeed);
    } else {
      return []
    }
  }

  saveData = (data) => {
    const lastData = this.readData();
    const feedData = JSON.stringify(lastData.concat(data));
    localStorage.setItem('feed', feedData);
  }

  getFeedList = (url, index) => {
    this.setState({
      loading: true
    })
    const { useCache } = this.state;
    console.log('useCache', useCache);
    if (!useCache) {
      if (index === 1) {
        this.setState({
          useCache: true
        })
        Cookie.set('useCache', 'true');
      }
      return axios.get(url).then((r) => {
        const { data } = r;
        const cacheData = this.dealData(data);
        this.saveData(cacheData);
      })
    } else {
      console.log('加载缓存Feed');
      const _this = this;
      return new Promise(function (resolve, reject) {
        const cacheData = _this.readData();
        let { feedData } = _this.state;
        feedData = feedData.concat(cacheData)
        _this.setState({
          feedData,
          loading: false
        })
        resolve();
      })
    }
  }

  dealData = (data) => {
    let { feedData } = this.state;
    const fD = data.indexOf('XML') > -1 ? this.resolveFeedXML(data) : this.resolveFeedHTML(data);
    feedData = feedData.concat(fD)
    this.setState({
      feedData,
      loading: false
    })
    return feedData;
  }

  resolveFeedHTML = (data) => {
    const result = [];
    const items = $(data).find('item');
    items.each(function () {
      const el = $(this);
      const html = $(el.html());
      const description = el.find('description').html().replace('<!--[CDATA[', '').replace(']]-->', '');
      const title = el.find('title').html();
      const link = html[3].data;
      const time = moment(el.find('pubDate').html()).format('YYYY-MM-DD HH:mm');
      
      result.push({
        description,
        title,
        link,
        time
      })
    })
    return result;
  }
  resolveFeedXML = (data) => {
    const result = [];
    const items = $(data).find('entry');
    items.each(function () {
      const el = $(this);
      
      const description = el.find('content').text().replace('<!--[CDATA[', '').replace(']]-->', '').substr(0, 150) + '...';
      const title = el.find('title').text();
      const link = el.find('link').attr('href');
      const time = moment(el.find('updated').text()).format('YYYY-MM-DD HH:mm');

      result.push({
        description,
        title,
        link,
        time
      })
    })
    return result;
  }

  componentDidMount () {
    this.refreshFeed()
    // 一个小时刷新一次feed
    setInterval(() => {
      this.refreshFeed()
    }, 1000 * 60 * 60);
  }

  render() {
    const { feedData, loading } = this.state;
    return (
      <div className={loading ? 'loading container' : 'container'}>
        <List
          loading={loading}
          dataSource={feedData}
          renderItem={
            item => (
              <ListItem>
                <ListItemMeta
                  title={<a target="_blank" href={item.link}>{item.title}<span className="feed-time">{item.time}</span></a>}
                  description={item.description}
                />
              </ListItem>
            )
          }
        />
      </div>
    )
  }
}

export default Feed;